package com.example.demo.utils;

import org.springframework.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 电话校验工具.
 *
 * @author Mei Ruoxiao
 * @since 2020/9/7
 */
public class TelUtil {
    /**
     * 电话号11位
     */
    private static final int NUM_ELEVEN = 11;

    /**
     * 中国移动：China Mobile 13[4-9],147,148,15[0-2,7-9],165,170[3,5,6],172,178,18[2-4,7-8],19[5,8]
     */
    private static final String CM_NUM;

    /**
     * 中国联通：China Unicom 130,131,132,145,146,155,156,166,167,170[4,7,8,9],171,175,176,185,186
     */
    private static final String CU_NUM;

    /**
     * 中国电信：China Telecom 133,149,153,162,170[0,1,2],173,174[0-5],177,180,181,189,19[1,3,9]
     */
    private static final String CT_NUM;

    static {
        CM_NUM =
                "^((13[4-9])|(14[7-8])|(15[0-2,7-9])|(165)|(178)|(18[2-4,7-8])|(19[5,8]))\\d{8}|(170[3,5,6])\\d{7}$";
        CU_NUM =
                "^((13[0-2])|(14[5,6])|(15[5-6])|(16[6-7])|(17[1,5,6])|(18[5,6]))\\d{8}|(170[4,7-9])\\d{7}$";
        CT_NUM =
                "^((133)|(149)|(153)|(162)|(17[3,7])|(18[0,1,9])|(19[1,3,9]))\\d{8}|((170[0-2])|(174[0-5]))\\d{7}$";
    }

    public static boolean isTel(String tel) {

        return !StringUtils.isEmpty(tel)
                && tel.length() == NUM_ELEVEN
                && (isCmMobile(tel) || isCtMobile(tel) || isCuMobile(tel));
    }


    /**
     * 验证移动手机
     *
     * @return 验证通过返回true
     */
    private static boolean isCmMobile(final String tel) {
        Pattern p;
        Matcher m;
        boolean b;
        p = Pattern.compile(CM_NUM);
        m = p.matcher(tel);
        b = m.matches();
        return b;
    }

    /**
     * 验证联通手机
     *
     * @return 验证通过返回true
     */
    private static boolean isCuMobile(final String tel) {
        Pattern p;
        Matcher m;
        boolean b;
        p = Pattern.compile(CU_NUM);
        m = p.matcher(tel);
        b = m.matches();
        return b;
    }

    /**
     * 验证电信手机
     *
     * @return 验证通过返回true
     */
    private static boolean isCtMobile(final String tel) {
        Pattern p;
        Matcher m;
        boolean b;
        p = Pattern.compile(CT_NUM);
        m = p.matcher(tel);
        b = m.matches();
        return b;
    }
}
